package com.xxwy.ddu.security.code.authentication.qq.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxwy.ddu.security.code.authentication.qq.QQ;
import com.xxwy.ddu.security.code.authentication.qq.bean.QQUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * @author xxwy
 * on 2018/8/23 0023
 * AbstractOAuth2ApiBinding:非单例，每个人都要存储不一样的额token
 */
@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=&s";
    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?&oauth_consumer_key=%s&openid=%s";

    private String appId;
    private String openId;
    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String accessToken, String appId) {
        //发请求的时候accessToken作为策略查询参数
        super(accessToken,TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        String url = String.format(URL_GET_OPENID,accessToken);
        String result = getRestTemplate().getForObject(url,String.class);
        log.info("oppenid " + result);
        this.openId = StringUtils.substringBetween(result,"\"oppenid\":\"","\"}");
    }


    @Override
    public QQUserInfo getUserInfo() {
        String url = String.format(URL_GET_USERINFO,appId,openId);
        String result = getRestTemplate().getForObject(url,String.class);
        log.info(result);
        QQUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(result, QQUserInfo.class);
            userInfo.setOpen_id(openId);
            return userInfo;
        } catch (IOException e) {
            throw new RuntimeException("授权是转换QQuserInfo出错", e);
        }
    }
}
